package org.gl.training.planner.dao;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.gl.training.planner.model.DailyPlan;

@Stateless
public class DailyPlanDaoImpl implements DailyPlanDao {

	@PersistenceContext(unitName = "dailyPlannerPU")
	private EntityManager entityManager;

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	@SuppressWarnings("unchecked")
	@Override
	public DailyPlan getDailyPlan(Integer userId, Date date) {
		Query query = entityManager
				.createQuery("select distinct(dp) from DailyPlan dp join fetch dp.user join fetch dp.taskList where dp.user.id=:userId and dp.date=:date");
		query.setParameter("userId", userId);
		query.setParameter("date", date);

		List<DailyPlan> dailyPlanList = query.getResultList();

		if (dailyPlanList.size() > 1) {
			throw new IllegalStateException("Received more then one DailyPlan");
		}
		if (dailyPlanList.size() == 1) {
			return dailyPlanList.get(0);
		}
		return null;
	}

	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	@Override
	public DailyPlan findDailyPlan(Integer dailyPlanId) {
		return entityManager.find(DailyPlan.class, dailyPlanId);
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	@Override
	public DailyPlan save(DailyPlan dailyPlan) {
		return entityManager.merge(dailyPlan);
	}
}
